package com.gzxx.util;

import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * QRCodeUtil
 *
 * @author chenjing
 */
@Slf4j
public class QRCodeUtil {

    /**
     * 二维码颜色 黑色
     */
    private static final int BLACK = 0xFF000000;

    /**
     * 二维码颜色 白色
     */
    private static final int WHITE = 0xFFFFFFFF;

    public static BufferedImage genQRCode(String content, int width, int height) {
        Map<EncodeHintType, Object> hints = Maps.newHashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 0);
        //根据高度和宽度生成像素矩阵
        BitMatrix bitMatrix;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            log.error("生成二维码图片异常：{}", e);
            return null;
        }

        BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < bitMatrix.getWidth(); x++) {
            for (int y = 0; y < bitMatrix.getHeight(); y++) {
                //填充黑白两色
                image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    public static String ImageToBase64(BufferedImage image) {
        if (ObjectUtils.isEmpty(image)) {
            return null;
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", stream);
        } catch (IOException e) {
            log.error("图片转base64异常：{}", e);
            return null;
        }
        String base64 = Base64Utils.encode(stream.toByteArray());
        return base64;
    }

    /**
     * base64格式二维码
     */
    public static String qrCodeByBase64(String codeUrl) {
        BufferedImage bufferedImage = QRCodeUtil.genQRCode(codeUrl, 180, 180);
        String base64 = QRCodeUtil.ImageToBase64(bufferedImage);
        return base64;
    }
}
